package com.hxgz.steel.service.Impl;

import com.hxgz.steel.common.ServerResponse;
import com.hxgz.steel.dao.*;
import com.hxgz.steel.domain.*;
import com.hxgz.steel.service.UserService;
import com.hxgz.steel.util.MD5Util;
import com.hxgz.steel.util.WeixinCommenUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CompanyCertMapper companyCertMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private SocerManagerMapper socerManagerMapper;
    @Autowired
    private IntegralMapper integralMapper;
    @Autowired
    private MerchantMapper mMapper;


    public ServerResponse getUserById(Long userId) {
        userMapper.selectByPrimaryKey(userId);
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse updateUser(User user) {
        int count = userMapper.updateByPrimaryKeySelective(user);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("更新成功");
        }
        return ServerResponse.createByErrorMessage("更新失败");
    }


    @Override
    public ServerResponse userLogin(String username, String password, String code,
                                    HttpServletRequest request, HttpServletResponse httpServletResponse) {
        int count = userMapper.checkUsername(username);
        if (count == 0) {
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        String md5pass = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username, md5pass);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户密码有误");
        }
        if (StringUtils.isEmpty(user.getOpenid()) && StringUtils.isNotEmpty(code)) {
            String openId = WeixinCommenUtil.getOpenId(request, httpServletResponse, code);
            user.setOpenid((StringUtils.isEmpty(openId) || "null".equals(openId)) ? "" : openId);
            userMapper.updateByPrimaryKey(user);
        }
        user.setPassword(StringUtils.EMPTY);
        HashMap map = new HashMap();
        map.put("user", user);
        List<Address> addressList = addressMapper.getAddressList(user.getId());
        map.put("address", addressList);
   /* //新增获取登陆用户的状态
    Merchant merchant = mMapper.getMerchantByuserId(user.getId());
    map.put("merchant",merchant);*/
        return ServerResponse.createBySuccess("登陆成功", map);
    }

    /**
     * 获取openId
     */
  /*@RequestMapping(value = "getOpeanId.do", method = RequestMethod.GET)
  public ServerResponse getOpeanId(HttpServletRequest request,
      HttpServletResponse response) {
    String code = request.getParameter("code");
    String openId = WeixinCommenUtil.getOpenId(request, response, code);
    log.info("session中得到的openId值为:>>" + String.valueOf(openId));
    return ServerResponse.createBySuccess("获取成功", openId);
  }*/
    @Override
    public ServerResponse smsLogin(String username, HttpServletRequest httpServletRequest,
                                   HttpServletResponse httpServletResponse, String code) {
        User user = userMapper.findByUserName(username);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        if (StringUtils.isEmpty(user.getOpenid()) && StringUtils.isNotEmpty(code)) {
            String openId = WeixinCommenUtil.getOpenId(httpServletRequest, httpServletResponse, code);
            user.setOpenid(openId);
            userMapper.updateByPrimaryKey(user);
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse register(String phone, String password) throws Exception {
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password)) {
            return ServerResponse.createByErrorMessage("请输入用户名和密码");
        }
        //验证用户名称
        int count = userMapper.checkUsername(phone);
        if (count > 0) {
            return ServerResponse.createByErrorMessage("用户名已存在");
        }
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        user.setStatus(0);
        user.setPassword(MD5Util.MD5EncodeUtf8(password));
        int inscount = userMapper.insertSelective(user);
        //注册往积分明细添加数据
        Long integralId = Long.valueOf(1);
        SocerManager socerManager = socerManagerMapper.selectByPrimaryKey(integralId);
        if (new Integer(1).equals(socerManager.getStatus())) {
            user.setScore(Integer.valueOf(socerManager.getSocer()));
            int isUpdateUser = userMapper.updateByPrimaryKeySelective(user);
            Integral integral = new Integral();
            integral.setUserId(user.getId());
            integral.setInSource(integralId);
            integral.setType(0);
            integral.setInChange(Integer.valueOf(socerManager.getSocer()));
            int isSuccess = integralMapper.insertSelective(integral);
            if (inscount == 0 || isSuccess == 0 || isUpdateUser == 0) {
                throw new Exception();
            }
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse updatePwd(String phone, String password) {
        User user = new User();
        user.setUsername(phone);
        user.setPassword(MD5Util.MD5EncodeUtf8(password));
        int count = userMapper.updatePwdByName(user);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("修改成功");
        }
        return ServerResponse.createByErrorMessage("修改失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse companyCert(CompanyCert companyCert) {
        companyCertMapper.deleteByUserId(companyCert.getUserId());
        //提交前验证是否有过提交
//    CompanyCert hascom = companyCertMapper.queryCertByUserId(companyCert.getUserId());
//    if (hascom != null && hascom.getStatus() == 0) {
//      return ServerResponse.createByErrorMessage("无需重复申请");
//    }
        companyCert.setStatus(0);//审核状态:0待审核，1审核通过，2审核不通过
        int count = companyCertMapper.insertSelective(companyCert);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("提交成功");
        }
        return ServerResponse.createBySuccessMessage("提交失败");
    }

    @Override
    public ServerResponse companyCertInfo(Long userId) {
        CompanyCert companyCert = companyCertMapper.queryCertByUserId(userId);
        return ServerResponse.createBySuccess(companyCert);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse relieveBinding(Long userId) {
        User user = new User();
        user.setId(userId);
        user.setBankNo(StringUtils.EMPTY);
        if (userMapper.updateByPrimaryKeySelective(user) > 0) {
            return ServerResponse.createBySuccessMessage("解绑成功");
        }
        return ServerResponse.createByErrorMessage("解绑失败");
    }

    @Override
    public ServerResponse getUserInfomation(Long userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        user.setPassword(StringUtils.EMPTY);
        user.setOpenid(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    @Override
    public ServerResponse getUserRole(Long userId) {
        //0未认证用户  1已认证用户，未认证店铺  2已认证用户，已认证店铺  3已认证用户，已认证公司,店铺已禁用
        Integer roleStatus = 0;//未认证用户
        if (userId == null) {
            roleStatus = 0;//未认证用户
        } else {
            Integer status = userMapper.getRoleStatusById(userId);
            if (status == 3) {
                roleStatus = 1;//已认证用户，未认证公司
                //Integer mMtatus = mMapper.getRoleStatusById(userId);
                Integer mMtatus = companyCertMapper.getRoleStatusById(userId);
                if (mMtatus != null && 2 == mMtatus) {
                    roleStatus = 2;//已认证用户，已认证公司
                    Integer mMStatus = mMapper.getRoleStatusById(userId);
                    if (mMStatus != null && 3 == mMStatus) {
                        roleStatus = 3;//已认证用户，已认证公司,店铺已禁用
                    }
                }
            } else {
                roleStatus = 0;
            }
        }
        return ServerResponse.createBySuccess(roleStatus);
    }

    @Override
    public User getUserByUserId(Long userId) {
        //根据用户id查询用户当前信息
        User user = userMapper.selectByPrimaryKey(userId);
        return user;
    }

    @Override
    public ServerResponse checkUserStatus(Long userId) {
        Integer userStatus;
        Integer status = userMapper.getRoleStatusById(userId);
        if (status!=null && status == 3) {
            userStatus = 2;
            Integer mMtatus = companyCertMapper.getRoleStatusById(userId);
            if (mMtatus!=null && mMtatus == 2) {
                userStatus = 3;
                Integer mMStatus = mMapper.getRoleStatusById(userId);
                if (mMStatus!=null && mMStatus == 2) {
                    userStatus = 4;
                }
            }
        } else {
            //已登陆但未认证用户
            userStatus = 1;
        }
        return ServerResponse.createBySuccess(userStatus);
    }

}
